package com.epfresh.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.epfresh.R;
import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.bean.SearchBean;
import com.epfresh.bean.VoiceResult;
import com.epfresh.global.BaseActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

public class SearchByStoreActivity extends BaseActivity implements EventListener {

    static final String TAG = "SearchActivity";
    ImageView ivBack;
    ImageView ivSearch;
    EditText etContent;
    TextView tvSearch;
    ImageView ivDelete;
    View llHot, rlHistory, rlAutomatic;
    HorizontalScrollView hsvHot;
    ListView lvHistory, lvAutomatic;

    ArrayList<String> hotList = new ArrayList<>();
    ArrayList<String> autoList = new ArrayList<>();
    InputMethodManager inputMethodManager;

    ArrayList<SearchBean> beanList;

    private View rl_tips;
    private ImageView img_voice_identify;
    private TextView txt_tip1, txt_tip2, txt_tip3, txt_tip4, txt_tip5;
    private GifImageView img_gif_voice;
    private TextView txt_voice_search;
    private ImageView img_cancel;

    private boolean isVoiceRunning = false;
    private boolean haveRecording = false;
    private boolean activeShutdown = false;
    private EventManager asr;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
        initVoiceConfigure();
        inputMethodManager.showSoftInput(etContent, InputMethodManager.SHOW_FORCED);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        setContentView(R.layout.activity_search);
        hsvHot = (HorizontalScrollView) findViewById(R.id.hsv_hot);
        llHot = findViewById(R.id.ll_hot);
        rlHistory = findViewById(R.id.rl_history);
        rlAutomatic = findViewById(R.id.rl_automatic);
        lvHistory = (ListView) findViewById(R.id.lv_history);
        lvAutomatic = (ListView) findViewById(R.id.lv_automatic);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        etContent = (EditText) findViewById(R.id.et_content);
        etContent.setHint("请输入商品名称");
        tvSearch = (TextView) findViewById(R.id.tv_search);
        tvSearch.setOnClickListener(this);
        ivDelete = (ImageView) findViewById(R.id.iv_delete);
        ivDelete.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        rlAutomatic.setVisibility(View.GONE);
        rlHistory.setVisibility(View.GONE);
        llHot.setVisibility(View.GONE);

        rl_tips = findViewById(R.id.rl_tips);
        img_voice_identify = findViewById(R.id.img_voice_identify);
        txt_tip1 = findViewById(R.id.txt_tip1);
        txt_tip2 = findViewById(R.id.txt_tip2);
        txt_tip3 = findViewById(R.id.txt_tip3);
        txt_tip4 = findViewById(R.id.txt_tip4);
        txt_tip5 = findViewById(R.id.txt_tip5);
        img_gif_voice = findViewById(R.id.img_gif_voice);
        txt_voice_search = findViewById(R.id.txt_voice_search);
        img_cancel = findViewById(R.id.img_cancel);

        txt_voice_search.setOnClickListener(this);
        img_cancel.setOnClickListener(this);

/*
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(etContent.getText())) {
                    rlHistory.setVisibility(View.VISIBLE);
                    llHot.setVisibility(View.VISIBLE);
                    rlAutomatic.setVisibility(View.GONE);
                    historyAdapter.notifyDataSetChanged();
                    //inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(),0);
                } else {
                    tvAutomatic.setText("搜索“" + etContent.getText().toString() + "”店铺");
                    rlHistory.setVisibility(View.GONE);
                    llHot.setVisibility(View.GONE);
                    rlAutomatic.setVisibility(View.VISIBLE);
                    requestAuto();
                    inputMethodManager.showSoftInput(etContent, InputMethodManager.SHOW_FORCED);
                }
            }
        });
*/

        etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    if (TextUtils.isEmpty(etContent.getText().toString())) {
                        return true;
                    }
                    if (!VerificationUtils.isValid(etContent.getText().toString())) {
                        toast("请删除特殊字符");
                        return true;
                    }
                    Intent goodsList = new Intent(SearchByStoreActivity.this, SearchGoodsActivity.class);
                    goodsList.putExtra("title", etContent.getText().toString());
                    goodsList.putExtra("type_view", 2);
                    goodsList.putExtra("storeId", getIntent().getStringExtra("storeId"));
                    startActivity(goodsList);
                    inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });
    }

    protected View getToolBar() {
        View actionbar = this.inflaterView(R.layout.toolbar_search_goods_store, null);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, this.getResources().getDimensionPixelSize(com.epfresh.api.R.dimen.action_bar_height));
        actionbar.setLayoutParams(lp);
        return actionbar;
    }

    @Override
    protected void onToolbarBack() {
        inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
        super.onToolbarBack();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                // 返回上一页
                inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
                finish();
                break;
            case R.id.tv_search:
                // 搜商品
                if (TextUtils.isEmpty(etContent.getText().toString())) {
                    return;
                }

                HashMap<String, String> test_new = new HashMap<>();
                test_new.put("map_new_key_1" + getUser().getAccountId(), etContent.getText().toString() + "map_value_0001");
                test_new.put("map_new_key_2" + getUser().getAccountId(), etContent.getText().toString() + "map_value_0002");

                MobclickAgent.onEventValue(this, "purchaser_search_goods", test_new, 1);

/*                HashMap<String , String> test_old = new HashMap<>();
                test_old.put("map_old_key_1"+getUser().getAccountId(),etContent.getText().toString()+"map_value_0001");
                test_old.put("map_old_key_2"+getUser().getAccountId(),etContent.getText().toString()+"map_value_0002");

                onEvent(this, "purchaser_search_goods", test_old,100);*/

                if (!VerificationUtils.isValid(etContent.getText().toString())) {
                    toast("请删除特殊字符");
                    return;
                }
                Intent goodsList = new Intent(this, SearchGoodsActivity.class);
                goodsList.putExtra("title", etContent.getText().toString());
                goodsList.putExtra("type_view", 2);
                goodsList.putExtra("storeId", getIntent().getStringExtra("storeId"));
                startActivity(goodsList);
                inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
                //historyAdapter.notifyDataSetChanged();
                break;

            case R.id.txt_voice_search:
                if (!isVoiceRunning) {
                    audioPermissionCheck();
                } else {
                    activeShutdown = true;
                    voiceActiveStop();
                }
                break;

            case R.id.img_cancel:
                voiceCancel();
                break;
            default:
                break;
        }
    }

    //************************************************************百度语音搜索*********************************************************************************


    private void initVoiceConfigure() {
        asr = EventManagerFactory.create(this, "asr");
        asr.registerListener(this);
    }

    /**
     * 按钮状态切换
     *
     * @param voiceCheck 是否可以录音 true：可以 false：不可以
     */
    private void updateButtonStatus(boolean voiceCheck) {
        if (voiceCheck) {
            txt_voice_search.setText("语音搜索");
            txt_voice_search.setTextColor(Color.parseColor("#24af75"));
            txt_voice_search.setBackgroundResource(R.drawable.btn_voice_search);
            Drawable drawable = SearchByStoreActivity.this.getResources().getDrawable(R.mipmap.icon_microphone_green);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            txt_voice_search.setCompoundDrawables(drawable, null, null, null);
            img_cancel.setVisibility(View.GONE);
            isVoiceRunning = false;
        } else {
            txt_voice_search.setText("结束录音");
            txt_voice_search.setTextColor(Color.parseColor("#ffffff"));
            txt_voice_search.setBackgroundResource(R.drawable.btn_voice_no_search);
            Drawable drawable = SearchByStoreActivity.this.getResources().getDrawable(R.mipmap.icon_microphone_white);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            txt_voice_search.setCompoundDrawables(drawable, null, null, null);
            img_cancel.setVisibility(View.VISIBLE);
            isVoiceRunning = true;
        }
    }

    /**
     * 基于SDK集成 发送开始事件
     * 点击开始按钮
     * 测试参数填在这里
     */
    private void voiceStart() {
        updateButtonStatus(false);
        //基于SDK集成,设置识别参数
        Map<String, Object> params = new LinkedHashMap<>();
        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
        String json; // 可以替换成自己的json
        json = new JSONObject(params).toString(); // 这里可以替换成你需要测试的json
        asr.send(SpeechConstant.ASR_START, json, null, 0, 0);
    }

    /**
     * 点击停止按钮
     * 基于SDK集成 发送停止事件
     */
    private void voiceActiveStop() {
        updateButtonStatus(true);
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);
    }

    private void voiceAutoStop(boolean haveResult) {
        if (!activeShutdown) {
            updateButtonStatus(true);
        }
        if (haveResult) {
            actionbar.setVisibility(View.VISIBLE);
            rl_tips.setVisibility(View.GONE);
        }
        activeShutdown = false;
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);
    }

    private void voiceCancel() {
        updateButtonStatus(true);
        actionbar.setVisibility(View.VISIBLE);
        rl_tips.setVisibility(View.GONE);
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);
    }

    @Override
    public void onEvent(String name, String params, byte[] bytes, int offset, int length) {
        Log.i("voice_flag:", name);
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_READY)) {
            //提示开始说话
            haveRecording = false;
            beginRecording();
        }

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_END)) {
            //说话结束提示开始识别
            beginIdentify();
        }

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_FINISH)) {
            if (!haveRecording) {
                showNoVoice();
            } else {
                showVoiceResult();
            }
        }
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {

            if (params != null) {
                VoiceResult voiceResult = VoiceResult.parseJson(params);
                // 识别结果
                String[] results = voiceResult.getResultsRecognition();
                if (voiceResult.isFinalResult()) {
                    // 最终识别结果，长语音每一句话会回调一次
                    haveRecording = true;
                    txt_tip1.setText(results[0]);
                }
            }

        }
    }


    private void beginRecording() {
        actionbar.setVisibility(View.GONE);
        rl_tips.setVisibility(View.VISIBLE);
        img_voice_identify.setVisibility(View.GONE);
        txt_tip1.setText("你可以试试这样说");
        txt_tip1.setTextColor(Color.parseColor("#313131"));
        txt_tip1.setVisibility(View.VISIBLE);
        txt_tip2.setVisibility(View.GONE);
        txt_tip3.setVisibility(View.VISIBLE);
        txt_tip4.setVisibility(View.VISIBLE);
        txt_tip5.setVisibility(View.VISIBLE);
        img_gif_voice.setVisibility(View.VISIBLE);
    }

    private void beginIdentify() {
        img_voice_identify.setVisibility(View.VISIBLE);
        txt_tip1.setVisibility(View.GONE);
        txt_tip2.setVisibility(View.GONE);
        txt_tip3.setVisibility(View.GONE);
        txt_tip4.setVisibility(View.GONE);
        txt_tip5.setVisibility(View.GONE);
        img_gif_voice.setVisibility(View.GONE);
    }

    private void showVoiceResult() {
        img_voice_identify.setVisibility(View.GONE);
        txt_tip1.setTextColor(Color.parseColor("#313131"));
        txt_tip1.setVisibility(View.VISIBLE);
        txt_tip2.setVisibility(View.GONE);
        txt_tip3.setVisibility(View.GONE);
        txt_tip4.setVisibility(View.GONE);
        txt_tip5.setVisibility(View.GONE);
        img_gif_voice.setVisibility(View.GONE);
        autoSearch(txt_tip1.getText().toString());

    }

    private void showNoVoice() {
        img_voice_identify.setVisibility(View.GONE);
        txt_tip1.setTextColor(Color.parseColor("#f13d1a"));
        txt_tip1.setText("未检测到语音");
        txt_tip1.setVisibility(View.VISIBLE);
        txt_tip2.setVisibility(View.VISIBLE);
        txt_tip3.setVisibility(View.VISIBLE);
        txt_tip4.setVisibility(View.VISIBLE);
        txt_tip5.setVisibility(View.VISIBLE);
        img_gif_voice.setVisibility(View.GONE);
        voiceAutoStop(false);
    }

    private void autoSearch(final String keyWord) {

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                voiceAutoStop(true);
                toSearch(keyWord);
            }
        }, 1000);

    }

    private void toSearch(String keyWord) {
        etContent.setText(keyWord);
        etContent.setSelection(keyWord.length());
        tvSearch.performClick();
    }

    private void audioPermissionCheck() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
        } else {
            voiceStart();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    voiceStart();
                } else {
                    T.toast("请到设置中打开应用语音权限！");
                }
                break;
        }
    }

    @Override
    protected void onPause() {
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (img_gif_voice != null) {
            ((GifDrawable) img_gif_voice.getDrawable()).stop();
        }
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);
        asr.unregisterListener(this);
        super.onDestroy();
    }

}
